﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace XUtility
{
    public static class ObjectEx
    {
        /// <summary>
        /// 对象转json
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static String ToJson(this object obj, String dtFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss", Boolean enableNULL = false)
        {
            return JsonClass.ToJson(obj, dtFormat, enableNULL);
        }

        /// <summary>
        /// 对象转int32
        /// </summary>
        /// <param name="obj">对象</param>
        public static Int32 ToInt32(this object obj)
        {
            return obj.ToString().ToInt32();
        }

        /// <summary>
        /// 对象转int32
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="v">可空默认值,如果转换失败，同时v是空值，则返回日期最小值</param>
        public static DateTime ToDateTime(this object obj, DateTime? v = null)
        {
            return obj.ToString().ToDateTime(v);
        }

        /// <summary>
        /// 把当前对象转为另一个对象
        /// </summary>
        /// <typeparam name="T">新的对象类型</typeparam>
        /// <param name="obj">当前对象</param>
        /// <returns></returns>
        public static T MappingObject<T>(this object obj) where T : new()
        {
            return JsonClass.FromJson<T>(obj.ToJson());
        }
    }
}
